#include "./VideoPlayerNapi.h"
#include "./GlobalInfoMap.h"
#include "napi/adapter/VideoPlayerHandler.h"
#include "napi/common/OhosLog.h"
#include "napi/video/GlobalInfoMap.h"
#include "napi/common/native_common.h"
#include <bits/alltypes.h>
#include <js_native_api.h>
#include <js_native_api_types.h>


static const int32_t PLAYING = 0;
static const int32_t PAUSED = 1;
static const int32_t STOPPED = 2;
static const int32_t COMPLETED = 3;
static const int32_t PREPARED = 4;
static const int32_t UPDATING = 5;
static const int32_t ERROR = 6;

napi_value VideoPlayerNapi::onVideoCallBack(napi_env env, napi_callback_info info) {

    napi_status status;
    size_t argc = 5;
    napi_value args[5];
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
    if (argc != 5) {
        napi_throw_type_error(env, NULL, "Wrong number of arguments");
        return nullptr;
    }

    napi_valuetype valuetype;
    status = napi_typeof(env, args[0], &valuetype);
    if (status != napi_ok) {
        return nullptr;
    }
    if (valuetype != napi_number) {
        napi_throw_type_error(env, NULL, "Wrong arguments");
        return nullptr;
    }
    
    status = napi_typeof(env, args[1], &valuetype);
    if (status != napi_ok) {
        return nullptr;
    }
    if (valuetype != napi_number) {
        napi_throw_type_error(env, NULL, "Wrong arguments");
        return nullptr;
    }

    int32_t viewTag;
    NAPI_CALL(env, napi_get_value_int32(env, args[0], &viewTag));
    int32_t event;
    NAPI_CALL(env, napi_get_value_int32(env, args[1], &event));

    GlobalInfoMap *globalInfoMap = GlobalInfoMap::getInstance();
    VideoPlayerInfo *videoPlayerInfo = globalInfoMap->getVideoPlayerInfo(viewTag);
    if(videoPlayerInfo == nullptr){
        OHOS_LOGE("VideoPlayerNapi::videoPlayerInfo is null");
        return nullptr;
    }
    
    if (event == PREPARED) {
        int32_t totalTime;
        NAPI_CALL(env, napi_get_value_int32(env, args[3], &totalTime));
        videoPlayerInfo->totalTime = totalTime;

        VideoPlayerHandler::getInstance()->onPreparedEvent(viewTag, videoPlayerInfo);
    }

    if (event == PLAYING ||event == PAUSED || event == COMPLETED) {
        bool isPlay;
        NAPI_CALL(env, napi_get_value_bool(env, args[2], &isPlay));
        videoPlayerInfo->isPlay = isPlay;
        if(event == COMPLETED){
            VideoPlayerHandler::getInstance()->onEndedEvent(viewTag, videoPlayerInfo);
        }
    }

    if (event == UPDATING) {
        int32_t currentTime;
        NAPI_CALL(env, napi_get_value_int32(env, args[4], &currentTime));
        videoPlayerInfo->currentTime = currentTime;
    }
    
    if(event == ERROR){
        VideoPlayerHandler::getInstance()->onFailedEvent(viewTag, videoPlayerInfo);
    }

    return nullptr;
}
